#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@date: 2011-10-23
@author: shell.xu
'''
import os
import sys
import urllib, urllib2
import logging
import urlparse

class Brower(object):
    fakeagent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1'
    fakeencoding = 'gzip,deflate,sdch'

    def __init__(self, debug = False):
        p = [urllib2.HTTPCookieProcessor(),]
        if debug: p.append(urllib2.HTTPHandler(debuglevel = 1))
        self.sess = urllib2.build_opener(*p)
        self.fake_headers = {}

    def set_user_agent(self, user_agent):
        if user_agent is None: del self.fake_headers['User-Agent']
        elif user_agent is True:
            self.fake_headers['User-Agent'] = self.fakeagent
        else: self.fake_headers['User-Agent'] = user_agent

    def set_accept_encoding(self, accept_encoding):
        if accept_encoding is None: del self.fake_headers['Accept-Encoding']
        elif accept_encoding is True:
            self.fake_headers['Accept-Encoding'] = self.fakeencoding
        else: self.fake_headers['User-Agent'] = accept_encoding

    def add_header(self, req, headers):
        if self.fake_headers:
            if headers is None: headers = {}
            headers.update(self.fake_headers)
        if headers:
            for k, v in headers.items(): req.add_header(k, v)

    def get(self, url, headers = None):
        logging.debug('get url: ' + url)
        req = urllib2.Request(url)
        self.add_header(req, headers)
        res = self.sess.open(req)
        return res.info(), res.read()

    def post(self, url, form, headers = None):
        logging.debug('post url: ' + url)
        req = urllib2.Request(url)
        req.add_data(urllib.urlencode(form))
        self.add_header(req, headers)
        res = self.sess.open(req)
        return res.info(), res.read()

def urldecode(url):
    rslt = {}
    for i in urlparse.urlparse(url).query.split('&'):
        k, v = i.split('=', 1)
        rslt[k] = urllib.unquote(v)
    return rslt
